package cn.learn.dao.impl;

import cn.learn.domain.ElasticsearchQuery;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.List;

/**
 * es的地图查询类，重构，尚未完成
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年07月15日10:43
 */
@Repository
public class GeoElasticsearchQuery {

    private final RestHighLevelClient restHighLevelClient;

    public GeoElasticsearchQuery(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    /**
     * 当前页
     */
    private int currentPage = 1;
    /**
     * 页面大小
     */
    private int size        = 10;


    /**
     * 页码的起始索引
     */
    private int getStartIndex() {
        return (currentPage - 1) * size;
    }


    private SearchHits highLevelQuery(String index) throws IOException {
        //创建一个搜索请求
        SearchRequest searchRequest = new SearchRequest(index);
        //创建一个搜索资源对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder builder = this.customizedQuery();
        searchSourceBuilder.query(builder);
        //分页处理，在1w条数据内；用from size做最好，默认就是top10
        //默认查询前1w条数据
        if (this.getStartIndex() > -1 && size > 0) {
            searchSourceBuilder.from(currentPage).size(size);
        }

        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        return search.getHits();
    }


    public SearchHits geoPolygon(ElasticsearchQuery qo, List<GeoPoint> points) throws IOException {
        this.currentPage = qo.getFrom();
        this.size = qo.getSize();

        return this.highLevelQuery(qo.getIndex());
    }


    protected BoolQueryBuilder customizedQuery() {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();


        builder.must(QueryBuilders.matchAllQuery());

        return builder;
    }


}
